package com.leexuan.ordersystem.actions;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.leexuan.ordersystem.db.ProductDB;
import com.leexuan.ordersystem.forms.ProductForm;

public class SearchProductAction extends Action {

	public SearchProductAction() {
		super();
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		ProductForm fm = (ProductForm) form;

		int type = Integer.parseInt(request.getParameter("type"));

		String sqlstr = "SELECT p.*,s.name AS sname FROM product AS p INNER JOIN sort AS s ON p.sid=s.sid WHERE 1=1 ";

		if (type == 1) {

			if (fm.getNumber() != "")
				sqlstr += "AND p.number LIKE '%" + fm.getNumber() + "%' ";
			if (fm.getName() != "")
				sqlstr += "AND p.name LIKE '%" + fm.getName() + "%' ";
			if (fm.getModel() != "")
				sqlstr += "AND p.model LIKE '%" + fm.getModel() + "%' ";
			if (fm.getSid() != 0)
				sqlstr += "AND p.sid=" + fm.getSid() + " ";
			if (fm.getNum() > 0)
				sqlstr += "AND p.num<" + fm.getNum() + " ";

		} else {
			System.out.print(fm.getNumber());

			if (fm.getNumber() != "")
				sqlstr += "AND p.number='" + fm.getNumber() + "' ";
			if (fm.getName() != "")
				sqlstr += "AND p.name='" + fm.getName() + "' ";
			if (fm.getModel() != "")
				sqlstr += "AND p.model='" + fm.getModel() + "' ";
			if (fm.getSid() != 0)
				sqlstr += "AND p.sid=" + fm.getSid() + " ";
			if (fm.getNum() > 0)
				sqlstr += "AND p.num<" + fm.getNum() + " ";

		}

		ProductDB db = new ProductDB();

		try {
			db.getConnection();

			ArrayList products = null;

			products = db.findProducts(sqlstr);

			HttpSession session = request.getSession();
			session.setAttribute("products", products);

			return mapping.findForward("success");

		} catch (Exception e) {

			return (new ActionForward(mapping.getInput()));
		} finally {
			try {
				db.closeConnection();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
